
import React, { useEffect, useState } from "react";
import Heand from "../component/heand"
import { useParams, useLocation } from "react-router-dom"
import get from "../api/api";
import "./index.css"
import { isLogined } from "./auth";
import axios from 'axios'
import { useNavigate } from "react-router-dom";
import { Input, Button, Popover,Modal } from 'antd';
import Cs from "./cs";

function Xq(props) {
    const navigate = useNavigate()
    const [xqpushimage, setXqpushimage] = useState(null)
    // const [form] = Form.useForm();
    const { objectId } = useParams();
    const location = useLocation();
    // const [one, setOne] = useState('')
    const people_id = sessionStorage.getItem('username')
    console.log(xqpushimage)
    const [newprice, setNewprice] = useState('')
    const [newname, setNewname] = useState('')
    const [people, setPeople] = useState('')
    const [showInput, setShowInput] = useState('');

const [visia,setVisia]=useState(false)




    const handlePriceChange = (event) => {
        setNewprice(event.target.value);
    };
    const handleNameChange = (event) => {
        setNewname(event.target.value);
    };

    const onOk= ()=>{
        setVisia(false)
    }
    const Ljgm = async (event) => {
        
        
        try {
            const response = await axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"people_id":"${people_id}","Commodity_id":"${objectId}"}`, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                }
            }).then((e) => {



                axios.put(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[0].objectId}`, {
                    pay: 'true',
                }, {
                    headers: {
                        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                        'Content-Type': 'application/json'
                    }
                }).then((e) => {
                    console.log(e.data); // 处理返回的数据
                    //   setShowInput(false);


                    window.location.reload()
                    console.log(newprice, "修改成功")


                    // 更新展示的数据
                })





            })


        } catch (error) {
            console.error(error);
        }

        onOk();

    }


    const handleSubmit = async (event) => {
        event.preventDefault();
        console.log('出发了')

        try {
            const response = await axios.put(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${objectId}`, {
                price: newprice,
            }, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                }
            }).then((e) => {
                console.log(e.data); // 处理返回的数据
                //   setShowInput(false);


                // window.location.reload()
                console.log(newprice, "修改成功")


                // 更新展示的数据
            })


        } catch (error) {
            console.error(error);
        }

        console.log(objectId, people_id)
        axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${objectId}"}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        }).then((e) => {
            // console.log(e.data.results[0].objectId)
            console.log(e)

            if (e.data.results.length !== 0) {
                axios.put(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[0].objectId}`, {

                    price: newprice
                }, {
                    headers: {
                        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                        'Content-Type': 'application/json'
                    }


                }
                ).then((e) => {
                    console.log(e.data); // 处理返回的数据
                    //   setShowInput(false);



                    console.log(newprice, "修改成功")
                    window.location.reload()
                    // window.location.reload()
                    // 更新展示的数据

                }).catch((error) => {
                    console.log(error)
                })
            }
            else {
                window.location.reload()
            }
        }).catch((error) => {
            console.log(error)
            // console.log(e.data.results[0].objectId)
        })




    };


    const handlename = async (event) => {
        event.preventDefault();
        console.log('出发了')

        try {
            const response = await axios.put(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${objectId}`, {
                xiangqing: newname,
            }, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json'
                }
            }).then((e) => {
                console.log(e.data); // 处理返回的数据
                //   setShowInput(false);



                console.log(newprice, "修改成功")

                // window.location.reload()
                // 更新展示的数据
            })


        } catch (error) {
            console.error(error);
        }


        axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${objectId}"}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                'Content-Type': 'application/json'
            }
        }).then((e) => {
            // console.log(e.data.results[0].objectId)
            console.log(e)
            if (e.data.results.length !== 0) {
                axios.put(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[0].objectId}`, {

                    xiangqing: newname
                }, {
                    headers: {
                        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                        'Content-Type': 'application/json'
                    }


                }
                ).then((e) => {
                    console.log(e.data); // 处理返回的数据
                    //   setShowInput(false);

                    window.location.reload()

                    console.log(newprice, "修改成功")



                }).catch((error) => {
                    console.log(error)
                })
            }
            else {
                window.location.reload()
            }

        }).catch((error) => {
            console.log(error)
        })




    };


    // 添加商品
    const push = async (e) => {
        e.preventDefault();
        try {
            const data = {
                image: listt.image,
                xiangqing: listt.xiangqing,
                price: listt.price,
                Commodity_id: objectId,
                people_id: people_id
            };
            //   console.log(data)
            const response = await axios.post(
                'https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food', data, {
                headers: {

                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    'Content-Type': 'application/json',
                },
            }).then((res) => {
                // console.log(res)
                window.location.reload()
            });


        } catch (error) {
            console.error('Error adding product:已添加', error);
        }
    }



    // const { Commodity_id } = useParams();
    const [listt, setListt] = useState(null)
    const [list, setList] = useState(null)
    var valuee = "";
    var lj = "";
    // console.log({ objectId })
    // console.log(objectId)
    //    componentDidMount
    // 获取商品信息
    // const Commodity_id=objectId
    //    useEffect(()=>{
    //     People()
    //    })

    const [spname, setSpname] = useState('')
    const div = (
        <div>
            { }
        </div>
    )


    


    useEffect(() => {
        // console.log(objectId)












        if (isLogined() === false) {
            navigate('/login')
        }
        console.log(xqpushimage)

        get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${objectId}`, {
            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            "Content-Type": ""
        })
            .then((res) => {
                setListt(
                    res
                )
                setSpname(res.xiangqing)
                console.log(res)



            })
            .catch((error) => {
                // console.log(error);
            });
        // 检查是否添加购物车

        get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"people_id":"${people_id}"}`, {
            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            "Content-Type": ""
        })
            .then((res) => {
                setList(res.results
                )



            })
            .catch((error) => {
                console.log(error);


            });

        get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${objectId}"}`,
            {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                "Content-Type": ""
            }
        ).then((res) => {
            //    console.log(res,'123333333333333333333333333')
            if (res.results.length !== 0) {
                setShowInput(res.results[0])
            }
        })


        get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${objectId}`, {
            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            "Content-Type": ""
        })
            .then((res) => {

                axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/people?where={"username":"${res.people_id}"}`, {
                    headers: {
                        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                        "Content-Type": ""
                    }
                }).then((res) => {
                    console.log(res)
                    if (res.data.results.length !== 0) {


                        setPeople(
                            res.data.results[0]
                        )
                    }
                })
                // console.log(res)



            })
            .catch((error) => {
                // console.log(error);
            });

        request()



    }, []);

    const row = [];
    const request = () => {
        get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image?where={"image_id":"${objectId}"}`, {
            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
            "Content-Type": "application/json"
        }).then((res) => {
            setXqpushimage(res.results)
            // console.log(xqpushimage)
            // console.log(res.results)


            // console.log(row)
        })
    }

    const delect = async (delectId) => {

        try {
            const response = await axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image/${delectId}`, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    "Content-Type": ""
                }

            }).then((res) => {
                // console.log(delectid)
                window.location.reload()
                console.log("删除成功")

            });

        } catch (error) {
            console.log(error);
        }
    }

    var glynon = 'none'
    if (location.state !== null) {
        if (location.state.gly === 1) {
            glynon = ''
            console.log(glynon)
        }
        else {
            glynon = 'none'
            console.log(glynon)
        }
    }




    (xqpushimage || []).forEach((item) => {
        row.push(
            <div className="pushimagediv" key={item.objectId}>
                <img className="pushimage" key={item.objectId} src={item.image_url} />
                <span style={{ display: glynon }} onClick={() => delect(item.objectId)}>删除</span>
            </div>



        )
    })


    //  var sub='';
    var isnon = 'none'
    // var sec = ""
    // console.log(list)
    let i = 0
    if (listt === null) {
        return 'Loding...'
    }
    else {
        console.log(showInput)
        if (showInput.pay == 'true') {
            lj = '已购买'
        } else {
            lj = '立即购买'
        }

        if (list !== null) {
            console.log('开始循环执行')
            console.log(list)
            if (list.length === 0) {
                valuee = '加入购物车'
                isnon = 'none'
            }
            else {

                // console.log(list)
                for (let i = 0; i < list.length; i++) {

                    console.log(i)
                    if (list[i].Commodity_id === objectId) {
                        valuee = '已添加购物车'
                        isnon = ''
                        break
                        // console.log(list[i].Commodity_id,objectId)
                    }
                    else {
                        valuee = '加入购物车'
                        isnon = 'none'
                        // console.log(list[i],value)
                        // console.log(list[i].Commodity_id,objectId)
                        console.log('也执行了')
                    }
                    console.log(list[i], valuee)


                }
            }



        }

        console.log(valuee)



    }
    var sec = ''
    if (listt.people_id === people_id) {
        sec = 'none'
    }
    else {
        sec = ''
    }

    // 购买
    console.log(showInput)
    // if(showInput.data.results.length!=0){
    //     if(showInput.data.results[0].pay=='true')
    // {
    //     lj='已购买'
    // }
    // else{
    //     lj='立即购买'
    // }
    // }




    const delectname = async (event) => {
        event.preventDefault();

        axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${objectId}"}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                "Content-Type": ""
            }
        }).then((e) => {
            console.log(e)

            axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[0].objectId}`, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    "Content-Type": ""
                }
            }).then(() => {
                console.log("删除成功")
                window.location.reload()
            })

        })

    }
    const delectsp = (event) => {
        event.preventDefault();

        axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image?where={"image_id":"${objectId}"}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                "Content-Type": "application/json"
            }
        }).then((res) => {
            console.log(res)
            if (res.data.results[0].length !== 0) {
                axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/image/${res.data.results[0].objectId}`, {
                    headers: {
                        " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                        "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                        "Content-Type": "application/json"
                    }
                }).then((res) => {
                    // console.log(res)
                    console.log('附属图片删除成功')
                }).catch((error) => {
                    console.log(error)
                })
            }
        }).catch((error) => {
            console.log(error)
        })







        axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/bscs/${objectId}`, {
            headers: {
                " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                "Content-Type": "application/json"
            }
        }).then((res) => {
            console.log('删除成功')


            axios.get(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food?where={"Commodity_id":"${objectId}"}`, {
                headers: {
                    " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                    "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                    "Content-Type": ""
                }
            }).then((e) => {
                console.log(e)

                if (e.data.results.length !== 0) {
                    axios.delete(`https://r5ctn9z9.lc-cn-n1-shared.com/1.1/classes/food/${e.data.results[0].objectId}`, {
                        headers: {
                            " X-LC-Id": "r5CTN9z96pCW8mI8fx9YxOmw-gzGzoHsz",
                            "X-LC-Key": "8gSsl4Sz0ILMiQeMNMA8xQqg",
                            "Content-Type": ""
                        }
                    }).then(() => {
                        console.log("删除成功")

                        navigate('/dianpu')
                    }).catch((error) => {
                        console.log('出错', error)
                    })
                }
                navigate('/dianpu')


            })




        }).catch((error) => {
            console.log('删除失败', error)
        })
    }








    return (
        <div>
            <Heand />
            <div className="xqquanju">

                <div className="xiangqingfirst">
                    <form className="xqtop">
                        <div className="xqImage">
                            <img className="xqimage" src={listt.image} />
                        </div>
                        <div className="xqText">
                            <Popover content={spname}>
                                {listt.xiangqing}
                            </Popover>

                            <label className="newinput" style={{ display: glynon }}>

                                <Input className="xqinp" type="text" value={newname} onChange={handleNameChange} />
                            </label>
                            <button className="xqbt" style={{ display: glynon }} onClick={handlename} type="submit">更新名字</button>
                            <hr />
                        </div>


                        <div className="xqText2">
                            ¥{listt.price}

                            <label className="newinput" style={{ display: glynon }}>

                                <Input className="xqinp" type="text" value={newprice} onChange={handlePriceChange} />
                            </label>
                            <button className="xqbt" style={{ display: glynon }} onClick={handleSubmit} type="submit">更新价格</button>
                            <hr />
                        </div>


                        <div className="xqbutton">
                            <button style={{ display: sec }} onClick={push} className="xqgwc">{valuee}</button>
                            <Button style={{ display: isnon }} className="xqdelect" onClick={delectname}  >删除</Button>
                            <hr style={{ display: sec }} />
                        </div>


                        <div className="shangjia">
                            <div>商家：{people.username}</div>
                            <div>联系电话：{people.phone}</div>
                            <div>QQ：{people.qq}</div>
                            <div className="ljgmbt">
                                <Button style={{ display: isnon }} className="ljgm" onClick={(()=>{setVisia(true)})}  >{lj}</Button>
                                <Modal
                                title="确认购买"
                                open={visia}
                                onOk={Ljgm}
                                onCancel={onOk}
                                afterClose={onOk}
                                >
                                    <p>是否确认购买</p>
                                </Modal>
                            </div>
                        </div>
                        {/* <div className="ljgmbutton">
                            

                        </div> */}
                        <div style={{ display: glynon }} className="delectsp">
                            <Button onClick={delectsp} className="delectbutton">删除该商品</Button>
                        </div>
                    </form>



                </div>


                <div className="xqfood">
                    <span className="xqspan">商品详情</span>
                    <hr />
                    <div className="xqfoodtext">

                        <div style={{ display: glynon }}>

                            <Cs objectId={listt.objectId} />

                        </div>
                        {row}
                    </div>

                </div>


            </div>


        </div>
    )
}

export default Xq